<template>
  <div class="list-page">
    <tool-bar nav="" title="Api定义">

      <kp label="加载">
        <el-autocomplete
            v-model="$data.profile"
            :fetch-suggestions="querySearch"
            clearable
            style="display: inline-block; width:120px;line-height:24px;"
            placeholder="profile"
        />
        <el-button size="small"
                   @click="markdown_load"
                   type="primary">加载
        </el-button>
      </kp>


      <el-button @click="view_markdown()" style="margin-left: 10px;">生成-{{
          $data.selected_apis.length
        }}个接口文档
      </el-button>
      <el-button @click="gen_param_json()" style="margin-left: 10px;">收集-{{
          $data.selected_apis.length
        }}个接口的参数
      </el-button>

      <el-button @click="gen_encode_doc_json()" style="margin-left: 10px;">根据def-json生成映射</el-button>

      <el-button @click="$data.dlg_show=true;">导入swagger</el-button>
      <el-button @click="$data.api_dlg_show=true;">导入apiJson</el-button>
      <el-button @click="add_click()">添加</el-button>
    </tool-bar>

    <my-list
        ref="list"
        url="/dev/api-define/list"
        @param="preload"
        @loaded="procData"
        :page-size="$data.pageSize"
        store
        :query="$data.query"
        multi-check
    >

      <el-table-column align="center" label="产品线" width="130px">
        <template #header>
          <el-button @click="$data.edit_productLine=true" v-if="!$data.edit_productLine">编辑产品线
          </el-button>
          <template v-else>
            <el-button @click="save_productLine">保存</el-button>
            <el-button @click="$data.edit_productLine=false">取消</el-button>
          </template>
        </template>
        <template v-slot="scope">
          <el-input v-model="scope.row.productLine.code" placeholder="编码或名称"
                    v-if="$data.edit_productLine">{{
              scope.row.productLine.code
            }}
          </el-input>
          <div v-else>{{ scope.row.productLine.name }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="应用" prop="app" width="160px">
        <template #header>
          <el-button @click="$data.edit_app=true" v-if="!$data.edit_app">编辑应用</el-button>
          <template v-else>
            <el-button @click="save_app">保存</el-button>
            <el-button @click="$data.edit_app=false">取消</el-button>
          </template>
        </template>
        <template v-slot="scope">
          <el-input v-model="scope.row.app" v-if="$data.edit_app">{{
              scope.row.app
            }}
          </el-input>
          <div v-else>{{ scope.row.app }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="模块" prop="group" width="160px">
        <template #header>
          <el-button @click="$data.edit_group=true" v-if="!$data.edit_group">编辑模块</el-button>
          <template v-else>
            <el-button @click="save_group">保存</el-button>
            <el-button @click="$data.edit_group=false">取消</el-button>
          </template>
        </template>
        <template v-slot="scope">
          <el-input v-model="scope.row.group" v-if="$data.edit_group">{{
              scope.row.productLine.name
            }}
          </el-input>
          <div v-else>{{ scope.row.group }}</div>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" min-width="180px" max-width="240px">
        <template v-slot="scope">
          <div class="link" @click="view_click(scope.row)">{{ scope.row.name }}</div>
        </template>
      </el-table-column>
      <el-table-column align="left" label="地址" prop="url" width="320px"></el-table-column>
      <el-table-column align="center" width="200px">
        <template #header>
          <el-button
              round
              @click="toggle_markdown_click"
              size="small">
            反选Markdown
          </el-button>
        </template>
        <template #default="scope">
          <el-button type="warning" style="margin-left:0 !important"
                     v-if="$data.selected_apis.map(it=>it.id).includes(scope.row.id)"
                     round @click="markdown_list_remove(scope.row)"
                     title="移除生成markdown"
                     size="small">
            <i class="el-icon-minus"></i>M
          </el-button>
          <el-button type="warning"
                     v-else
                     plain
                     round @click="markdown_list_add(scope.row)"
                     title="添加以准备生成markdown" style="margin-left:0 !important"
                     size="small">
            <i class="el-icon-plus"></i>M
          </el-button>

          <el-button type="warning" style="margin-left:4px !important"
                     plain
                     round
                     title="执行"
                     @click="exec_open_click(scope.row)" size="small">
            执
          </el-button>
          <el-button type="warning" style="margin-left:4px !important"
                     plain
                     round
                     title="修改"
                     @click="edit_click(scope.row)" size="small">
            修
          </el-button>
          <el-button type="warning" style="margin-left:4px !important"
                     plain
                     round
                     title="复制"
                     @click="clone_click(scope.row)" size="small">
            复
          </el-button>
          <el-button type="warning" style="margin-left:4px !important"
                     plain
                     round
                     title="删除"
                     @click="delete_click(scope.row)" size="small">
            删
          </el-button>
        </template>
      </el-table-column>
      <template #query="scope">
        <kv label="产品线">
          <product-line v-model="scope.query.productLine"></product-line>
        </kv>
        <kv label="应用">
          <el-autocomplete
              v-model="scope.query.app"
              :fetch-suggestions="queryAppSearch"
              clearable
              placeholder="应用"
          />
        </kv>

        <kv label="关键字">
          <el-input v-model="scope.query.text"></el-input>
        </kv>
        <kv label="中英">
          <selector
              :clearable="true"
              :data="{CnInName:'名称含中文',NoCnInName:'名称无中文', CnInField:'字段含中文', NoCnInField:'字段无中文'}"
              v-model="scope.query.cnType"></selector>
        </kv>
      </template>


      <template #pager>
        <div style="flex:1">
          <el-button size="small" @click="batch_delete_click" :disabled="list && !list.getSelectionRows().length">删除所选
          </el-button>
        </div>
        <selector :data="[10,20,50,100,200,500]" v-model="$data.pageSize"></selector>
      </template>
    </my-list>

    <el-dialog v-model="$data.exec_dlg" width="66vw" :title="'执行 ' + $data.currentApiInstance.apiDefine.name"
               ref="exec" destroy-on-close>
      <kv label="Host">
        <el-input v-model="$data.exec.host">
          <template #prepend>http://</template>
        </el-input>
      </kv>
      <kv label="地址">{{ $data.currentApiInstance.apiDefine.url }}</kv>

      <kv label="认证头">
        <el-input v-model="$data.exec.authorization">
          <template #prepend>Authorization: Bearer</template>
        </el-input>
      </kv>

      <exec-api v-model="$data.currentApiInstance" ref="execApiCom">

        <el-button style="display: block;margin: auto;" type="primary" @click="exec_click">执行</el-button>

        <kv label="status">
          <label v-if="!$data.exec.status">{{ $data.exec.status }}</label>
          <el-tag v-else-if="$data.exec.status.Between(200,400)">{{ $data.exec.status }}</el-tag>
          <el-tag v-else-if="!$data.exec.status.Between(200,400)" type="warning" style="font-width: bold;">{{
              $data.exec.status
            }}
          </el-tag>
        </kv>

        <kv label="响应头">

          <div class="ps">
            <kp v-for="(value,key) in $data.exec.responseHeader" :key="key" :label="key">
              <label>{{ value }}</label>
            </kp>
          </div>
        </kv>
        <kv label="响应体">
          <preview-json :model-value=" JSON.parse( $data.exec.responseBody || '{}') "></preview-json>
        </kv>

      </exec-api>
    </el-dialog>

    <el-dialog v-model="$data.dlg_show" width="66vw" title="导入swagger" ref="imp">
      <kv label="产品线">
        <product-line v-model="$data.imp.productLineCode" chk="*"></product-line>
      </kv>
      <kv label="应用">
        <el-input v-model="$data.imp.app" chk="*"></el-input>
      </kv>
      <kv label="swagger url">
        <el-input v-model="$data.imp.swaggerUrl"
                  placeholder="http:xxx/v2/api-docs or http:xxx/v3/api-docs"
                  chk=": if( !value && !data.imp.swaggerJson ){ return 'swagger url , swagger json 必输入一项' } "/>
      </kv>
      <kv label="swagger file">

        <el-upload
            ref="upload"
            drag
            v-model:file-list="$data.files"
            :limit="1"
            :on-exceed="handleExceed"
            :auto-upload="false"
            :action="jv.SERVER_HOST + '/dev/api-define/import-swagger'"
            :headers="$data.uploadHeaders"
            :data="$data.imp"
            :on-success="upload_sucess"
            :on-error="upload_error"
        >
          <el-icon class="el-icon--upload">
            <upload-filled/>
          </el-icon>
          <div class="el-upload__text">
            拖动上传 或 点击上传
          </div>
          <template #tip>
            <div class="el-upload__tip">
              swagger json文件
            </div>
          </template>
        </el-upload>

      </kv>
      <kv label="类型">
        <selector v-model="$data.imp.part" :data="{model:'模型',api:'接口','':'全部'}"></selector>
      </kv>
      <kv label="包含模块样式">
        <selector v-model="$data.imp.includeModuleStyle" :data="{mb:'[模块]',sb:'(模块)',lb:'{模块}'}"
                  multi></selector>
      </kv>
      <kv label="排除模块样式">
        <selector v-model="$data.imp.excludeModuleStyle" :data="{mb:'[模块]',sb:'(模块)',lb:'{模块}'}"
                  multi></selector>
      </kv>
      <kv label="排除模块包含">
        <el-input v-model="$data.imp.excludeModuleContent"/>
      </kv>

      <kv label="包含名称样式">
        <selector v-model="$data.imp.includeApiStyle" :data="{mb:'[模块]',sb:'(模块)',lb:'{模块}'}"
                  multi></selector>
      </kv>

      <kv label="排除名称样式">
        <selector v-model="$data.imp.excludeApiStyle" :data="{mb:'[模块]',sb:'(模块)',lb:'{模块}'}"
                  multi></selector>
      </kv>
      <kv label="排除名称包含">
        <el-input v-model="$data.imp.excludeNameContent"/>
      </kv>
      <kv label="排除url包含">
        <el-input v-model="$data.imp.excludeUrlContent"/>
      </kv>
      <kv>
        <template #k>
          <div class="k">移除url 第一部分
            <remark>
              如果请求地址第一部分是网关，需要选中该项，把请求地址的第一部分移除。这里填写网关部分,如 api
            </remark>
          </div>
        </template>
        <el-input v-model="$data.imp.removePrefix"></el-input>
      </kv>
      <kv label="覆盖参数">
        <el-switch v-model="$data.imp.override"></el-switch>
      </kv>
      <kv>
        <el-button @click="import_click">确定</el-button>
      </kv>

    </el-dialog>


    <el-dialog v-model="$data.api_dlg_show" width="66vw" title="导入 api-json" ref="imp">
      <kv label="产品线">
        <product-line v-model="$data.apiImp.productLineCode" chk="*"></product-line>
      </kv>
      <kv label="应用">
        <el-input v-model="$data.apiImp.app" chk="*" @change="app_change"></el-input>
      </kv>
      <kv label="api-doc url">
        <el-input v-model="$data.apiImp.apiUrl"
                  placeholder="http://xxx.com/api/app-api/open/api-doc"/>
      </kv>
      <kv label="swagger file">
        <el-upload
            ref="upload"
            drag
            v-model:file-list="$data.files"
            :limit="1"
            :on-exceed="handleExceed"
            :auto-upload="false"
            :action="jv.SERVER_HOST + '/dev/api-define/import-api'"
            :headers="$data.uploadHeaders"
            :data="$data.apiImp"
            :on-success="upload_sucess"
            :on-error="upload_error"
        >
          <el-icon class="el-icon--upload">
            <upload-filled/>
          </el-icon>
          <div class="el-upload__text">
            拖动上传 或 点击上传
          </div>
          <template #tip>
            <div class="el-upload__tip">
              api-doc json-list文件
            </div>
          </template>
        </el-upload>
      </kv>

      <kv label="包含模块样式">
        <selector v-model="$data.apiImp.includeModuleStyle" :data="{mb:'[模块]',sb:'(模块)',lb:'{模块}'}"
                  multi></selector>
      </kv>
      <kv label="排除模块样式">
        <selector v-model="$data.apiImp.excludeModuleStyle" :data="{mb:'[模块]',sb:'(模块)',lb:'{模块}'}"
                  multi></selector>
      </kv>
      <kv label="排除模块包含">
        <el-input v-model="$data.apiImp.excludeModuleContent"/>
      </kv>

      <kv label="包含名称样式">
        <selector v-model="$data.apiImp.includeApiStyle" :data="{mb:'[模块]',sb:'(模块)',lb:'{模块}'}"
                  multi></selector>
      </kv>

      <kv label="排除名称样式">
        <selector v-model="$data.apiImp.excludeApiStyle" :data="{mb:'[模块]',sb:'(模块)',lb:'{模块}'}"
                  multi></selector>
      </kv>
      <kv label="排除名称包含">
        <el-input v-model="$data.apiImp.excludeNameContent"/>
      </kv>
      <kv label="排除url包含">
        <el-input v-model="$data.apiImp.excludeUrlContent"/>
      </kv>
      <kv>
        <template #k>
          <div class="k">移除url 第一部分
            <remark>
              如果请求地址第一部分是网关，需要选中该项，把请求地址的第一部分移除。这里填写网关部分,如 api
            </remark>
          </div>
        </template>
        <el-input v-model="$data.apiImp.removePrefix"></el-input>
      </kv>
      <kv label="覆盖参数">
        <el-switch v-model="$data.apiImp.override"></el-switch>
      </kv>
      <kv>
        <el-button @click="import_api_click">确定</el-button>
      </kv>

    </el-dialog>

    <el-dialog v-model="$data.markdown_dlg" width="80vw" height="80vh">
      <template #header>
        共: {{ ($data.selected_apis || []).length }} 个api
        <div>

          <kp label="文档根级别">
            <el-input v-model="$data.level" style="width: 60px;"></el-input>
            <el-button @click="view_markdown">确定</el-button>
          </kp>

          <kp label="是否生成示例" style="">
            <el-switch v-model="$data.example" style="height: 24px;" @click="view_markdown"></el-switch>
          </kp>


          <el-button size="small"
                     style="margin-left: 10px;"
                     @click="http_client_click"
                     type="primary"> 下载 HttpClient
          </el-button>

          <kp label="另存为" style="margin-left: 10px;">
            <el-input v-model="$data.profile" placeholder="profile"
                      style="display: inline-block; width:120px;line-height:24px;"/>
            <el-button size="small"
                       @click="markdown_save_as"
                       type="primary">保存
            </el-button>
          </kp>
        </div>

      </template>

      <div ref="tags" class="tags">
        <el-tag v-for="item in $data.selected_apis"
                :key="item.title" @close="markdown_handleClose(item)"
                closable
                :title="item.path">
          {{ item.name }}
        </el-tag>
        <el-button v-if="$data.selected_apis.length" size="small"
                   @click="markdown_clear_click" style="margin-left: 30px;"
                   type="primary">清除
        </el-button>
        <el-button v-if="$data.selected_apis.length" size="small"
                   @click="markdown_reload_list" style="margin-left: 30px;"
                   type="primary">重新加载
        </el-button>
      </div>
      <el-input :rows="18" type="textarea" v-model="$data.markdown"></el-input>
    </el-dialog>


    <el-dialog v-model="$data.markdown_param_json_dlg" :key="$data.pkg_version" width="80vw" height="80vh">
      <template #header>
        生成生义及接口混淆，共: {{ ($data.selected_apis || []).length }} 个api
        <el-button size="small" @click="$data.selected_apis = [];">清除</el-button>
      </template>

      <api-def-com :apis="$data.selected_apis" :level="$data.level"></api-def-com>
    </el-dialog>


    <el-dialog v-model="$data.markdown_encode_doc_dlg" :key="$data.pkg_version" width="80vw" height="80vh">
      <template #header>
        根据定义生成映射！
      </template>

      <api-def-doc-com :productLineCode="$data.query.productLine" :level="$data.level"
                       :app="$data.query.app"></api-def-doc-com>
    </el-dialog>

  </div>
</template>
<style scoped lang="scss">


</style>
<script setup>
/**
 * Created by CodeGenerator at 2023-10-16 23:06:13
 */

import {UploadFilled, ArrowDown} from '@element-plus/icons-vue'
import productLine from "@/component/product-line.vue";
import execApi from "@/component/exec-api.vue"
import previewJson from "../../../component/preview-json.vue";
import apiDefCom from "./api-def-com.vue"
import apiDefDocCom from "./api-def-doc-com.vue"

//定义 vue2的this,当前组件
const $self = getCurrentInstance();

//定义 $attrs
const $attrs = useAttrs();

//定义data
const $data = reactive({
  profile: "",
  group: "",
  groups: [],
  pageSize: 10,
  "level": 1,
  example: false,
  "edit_group": false,
  edit_app: false,
  edit_productLine: false,
  "selected_apis": [],
  "feign_list": [],
  "markdown_dlg": false,
  "markdown_param_json_dlg": false,
  "markdown_encode_doc_dlg": false,
  pkg_version: 1,
  "markdown_param_json": "",
  "markdown": "",
  "dlg_show": false,
  api_dlg_show: false,
  files: [],
  "imp": {
    "productLineCode": "",
    app: "",
    includeModuleStyle: [],
    excludeModuleStyle: [],
    includeApiStyle: [],
    excludeApiStyle: [],
    excludeUrlContent: "",
    excludeNameContent: "",
    excludeModuleContent: "",
    "override": true
  },

  "apiImp": {
    "productLineCode": "",
    app: "",
    includeModuleStyle: [],
    excludeModuleStyle: ["mb"],
    includeApiStyle: ["mb"],
    excludeApiStyle: [],
    excludeUrlContent: "",
    excludeNameContent: "",
    excludeModuleContent: "",
    "override": true
  },

  uploadHeaders: {
    token: "",
  },
  "query": {},
  exec_dlg: false,

  exec: {
    host: ""
  },
  currentApiInstance: {apiDefine: {}},
  HttpMethod: jv.enum.HttpMethod.getData(),
  ApiParameterTypeEnum: jv.enum.ApiParameterTypeEnum.getData(),
  ApiParameterStringTypeEnum: jv.enum.ApiParameterStringTypeEnum.getData(),
});


$data.uploadHeaders.authorization = jv.authorization;

const execApiCom = ref();
const list = ref();
const tags = ref();

const upload = ref();

const handleExceed = (files) => {
  upload.value.clearFiles()
  const file = files[0]
  file.uid = jv.random()
  upload.value.handleStart(file)
}


const querySearch = (queryString, cb) => {
  jv.$http.post("/dev/api-define-profile/profiles", {search: queryString}).then(res => {
    var list = res.data;
    cb(list.map(it => {
      return {value: it}
    }));
  });
}

const queryAppSearch = (queryString, cb) => {
  jv.$http.post("/dev/api-define/list-app", {search: queryString}).then(res => {
    var list = res.data;
    cb(list.map(it => {
      return {value: it}
    }));
  });
}

const save_group = function () {
  var data = list.value.getData().data.map(it => {
    return {id: it.id, group: it.group}
  });
  jv.$http.post("/dev/api-define/save-group", data).then(res => {
    jv.info("保存成功")
    $data.edit_group = false;
    loadData();
  })
};
const save_app = function () {
  var data = list.value.getData().data.map(it => {
    return {id: it.id, app: it.app}
  });
  jv.$http.post("/dev/api-define/save-app", data).then(res => {
    jv.info("保存成功")
    $data.edit_app = false;
    loadData();
  })
};
const save_productLine = function () {
  var data = list.value.getData().data.map(it => {
    return {id: it.id, productLine: it.productLine.code}
  });
  jv.$http.post("/dev/api-define/save-product-line", data).then(res => {
    jv.info("保存成功")
    $data.edit_productLine = false;
    loadData();
  })
}
const delete_query_click = async () => {
  await jv.confirm('要删除查询条件的所有数据吗？');

  let res = await jv.$http.post("/dev/api-define/delete-query", list.value.getQuery())
  loadData();
}
const batch_delete_click = async ids => {
  var rows = list.value.getSelectionRows();
  if (!rows.length) {
    return jv.info("请选择要删除的数据行");
  }

  await jv.confirm('要删除选中了的 ' + rows.length + ' 行吗？');
  let res = await jv.$http.post("/dev/api-define/batch-delete", rows.map(it => it.id))
  loadData();
}
const markdown_list_sort = function () {
  $data.selected_apis = $data.selected_apis.sort((a, b) => {
    if (a.productLine.code != b.productLine.code) {
      return a.productLine.code > b.productLine.code ? 1 : -1
    }
    if (a.group != b.group) {
      return a.group > b.group ? 1 : -1;
    }
  })
  jv.$saveData("selected_apis", $data.selected_apis);
};
const markdown_list_remove = function (row) {
  $data.selected_apis.removeItem(it => it.id == row.id);
  markdown_list_sort();
};


const toggle_markdown_click = () => {
  list.value.getData().data.forEach(row => {
    if ($data.selected_apis.map(it => it.id).includes(row.id)) {
      $data.selected_apis.removeItem(it => it.id == row.id);
    } else {
      $data.selected_apis.push(row);
    }
  });

  jv.$saveData("selected_apis", $data.selected_apis);
}

const markdown_list_add = function (row) {
  $data.selected_apis.removeItem(it => it.id == row.id);
  $data.selected_apis.push(row);
  markdown_list_sort();
};
const markdown_clear_click = function () {
  $data.selected_apis = [];
  view_markdown();
};
const markdown_reload_list = function () {
  jv.$http.post("/dev/api-define/list", {
    ids: $data.selected_apis.map(it => it.id),
    skip: 0,
    take: $data.selected_apis.length
  }).then(res => {
    $data.selected_apis = res.data.data;
    jv.$saveData("selected_apis", $data.selected_apis);
    $data.markdown = jv.dev.api_markdown($data.selected_apis);
  });
};

const markdown_load = function () {
  if (!$data.profile) {
    return jv.error("请选择profile名称");
  }
  jv.$http.post("/dev/api-define-profile/load", {
    name: $data.profile
  }).then(res => {
    $data.selected_apis = res.data.data;
    jv.$saveData("selected_apis", $data.selected_apis);
    $data.markdown = jv.dev.api_markdown($data.selected_apis);
  });
};
const markdown_save_as = function () {
  if (!$data.selected_apis.length) {
    return jv.error("请选择 api");
  }
  if (!$data.profile) {
    return jv.error("请输入另存为名称");
  }
  jv.$saveData("selected_apis", $data.selected_apis);

  jv.$http.post("/dev/api-define-profile/save-as", {
    ids: $data.selected_apis.map(it => it.id),
    name: $data.profile
  });
};
const http_client_click = function () {
  if (!$data.selected_apis.length) {
    return jv.error("请选择 api");
  }
  if (!$data.profile) {
    return jv.error("请选择 profile");
  }
  jv.$saveData("selected_apis", $data.selected_apis);
  jv.downloadFile(window.SERVER_HOST + "/dev/api-define/http-client/download?profile=" + $data.profile);
};

const gen_param_json = function () {
  $data.pkg_version++;
  $data.markdown_param_json_dlg = true;
}

const gen_encode_doc_json = function () {
  var query = list.value.getQuery();
  $data.query.productLine = query.productLine;
  $data.query.app = query.app;

  $data.pkg_version++;
  $data.markdown_encode_doc_dlg = true;
}


const view_markdown = function () {

  jv.$saveData("selected_apis", $data.selected_apis);
  $data.markdown = jv.dev.api_markdown($data.selected_apis, jv.asInt($data.level), $data.example);
  $data.markdown_dlg = true;
  // $data.sortable && $data.sortable.destroy();
//     nextTick(() => {
//         $data.sortable = Sortable.create(tags.value, {
// //  指定父元素下可被拖拽的子元素
//             handle: ".el-tag",
//             onEnd({newIndex, oldIndex}) {
//                 const currRow = $data.selected_apis.splice(oldIndex, 1)[0];
//                 $data.selected_apis.splice(newIndex, 0, currRow);
//                 view_markdown();
//             }
//         });
//     });
};

const view_feign = () => {
  jv.info("暂未实现");
}
const markdown_handleClose = function (item) {
  $data.selected_apis.removeItem(item);
  view_markdown();
};
const feign_list_sort = function () {
  $data.feign_list = $data.feign_list.sort((a, b) => {
    if (a.productLine.code != b.productLine.code) {
      return a.productLine.code > b.productLine.code ? 1 : -1
    }
    if (a.group != b.group) {
      return a.group > b.group ? 1 : -1;
    }
  })
  jv.$saveData("feign_list", $data.feign_list);
};
const feign_list_remove = function (row) {
  $data.feign_list.removeItem(it => it.id == row.id);
  feign_list_sort();
};
const feign_list_add = function (row) {
  $data.feign_list.removeItem(it => it.id == row.id);
  $data.feign_list.push(row);
  feign_list_sort();
};
const import_click = function () {

  jv.$saveData("imp", $data.imp);

  if (!$data.imp.swaggerUrl && !$data.files.length) {
    return jv.error("请输入 swaagger url 或 上传 swagger json");
  }

  if ($data.files.length) {
    upload.value.submit();
  } else {
    jv.$http.post("/dev/api-define/import-swagger", $data.imp).then(res => {
      loadData();
      jv.alert("导入成功");
    });
  }

};

const import_api_click = function () {
  jv.$saveData("apiImp", $data.apiImp);

  if (!$data.apiImp.apiUrl && !$data.files.length) {
    return jv.error("请输入 api-json url 或 上传 apiDoc");
  }

  if ($data.files.length) {
    upload.value.submit();
  } else {
    jv.$http.post("/dev/api-define/import-api", $data.apiImp).then(res => {
      loadData();
      jv.alert("导入成功");
    });
  }

};

const preload = function (param) {
//保存查询条件
//添加查询参数，修改分页参数等。
//param.type = jv.$route.params.type
};


const upload_sucess = () => {
  loadData();
  jv.info("导入成功");
}

const upload_error = () => {
  jv.error("上传失败");
}

const procData = function (res) {
  res.data.data.forEach(it => {
//如果是组合实体，设置 it.id=...
    jv.enum.HttpMethod.fillRes(it, "httpMethod");
  });
};


const loadData = function (pageNumber) {
  list.value.loadData(pageNumber);
};
const add_click = function () {
  jv.$router.push("/dev/api-define/add")
};
const edit_click = function (row) {
//记录上次点击行
  let rowId = row.id;
  list.value.setLastRow(row);
  jv.$router.push("/dev/api-define/edit/" + rowId)
};
const view_click = function (row) {
//记录上次点击行
  let rowId = row.id;
  list.value.setLastRow(row);
  jv.$router.push("/dev/api-define/view/" + rowId)
};

const delete_click = async function (row) {
  let rowId = row.id, rowName = row.name;
  await jv.confirm('确认删除 ' + rowName + ' 吗？');
  let res = await jv.$http.post("/dev/api-define/delete/" + rowId)
  loadData();
};
const clone_click = async function (row) {
  let rowId = row.id;
  let res = await jv.$http.post("/dev/api-define/clone/" + rowId)
  loadData();
};

const app_change = ev => {
  if (!$data.apiImp.apiUrl) {
    $data.apiImp.apiUrl = `https://test.huatuocloud.com/api/${$data.apiImp.app}/open/api-doc?name-style=%2B%5B%5D&group-style=!`
  }
}
const exec_open_click = row => {
  var def = {pageNo: 1, pageSize: 10};
  var defineId = row.id;
  // jv.$loadData("exec", v => $data.exec = v)
  // jv.$loadData("exec-body-" + defineId, v => Object.assign(def, v));

  $data.exec.host = "";
  $data.exec.authorization = "";
  $data.exec.status = "";
  $data.exec.responseHeader = {};
  $data.exec.responseBody = {};


  jv.$http.post("/dev/api-exec-test/latest/" + defineId).then(res => {

    var store = res.data.data;
    if (store) {
      $data.exec.host = store.host;
      $data.exec.authorization = store.authorization;
      $data.exec.status = store.status;
      $data.exec.responseHeader = store.responseHeader;
      $data.exec.responseBody = store.responseBody;

      def = store.parameters;
    }

    jv.recursionJson(row, it => {
      if (it.key in def) {
        if (!it.value) {
          it.value = def[it.key];
        }
      } else if ("order" in def) {
        def.order = "";
      }
    })

    $data.exec_dlg = true;
    $data.currentApiInstance = {apiDefine: row};

  })
}

const exec_click = () => {
  var defineId = $data.currentApiInstance.apiDefine.id;

  var body = execApiCom.value.getPostBody($data.currentApiInstance.apiDefine.requestBodyParameters.items);

  // jv.$saveData("exec", $data.exec)
  // jv.$saveData("exec-body-" + defineId, body)


  var post = Object.assign({}, {parameters: body, apiDefineId: defineId}, $data.exec);

  jv.$http.post("/dev/api-exec-test/exec-api", post).then(res => {
    var store = res.data.data;
    $data.exec.status = store.status;
    $data.exec.responseHeader = store.responseHeader;
    $data.exec.responseBody = store.responseBody;
  });
}

onMounted(() => {
  jv.$loadData("imp", v => $data.imp = v)
  jv.$loadData("apiImp", v => $data.apiImp = v)
  jv.$loadData("selected_apis", v => $data.selected_apis = v);

})

</script>

<style scoped lang="scss">

::v-deep(.cell) {
  button {
    margin-left: 8px;
    padding-left: 8px;
    padding-right: 8px;
  }
}

::v-deep(.el-upload-dragger) {
  padding: 20px;
}
</style>